<template>
  <div>
    <div
      v-loading.fullscreen.lock="fullscreenLoading"
      v-if="shippingWay && loaded"
    >
      <el-popover placement="left" trigger="hover">
        <el-divider content-position="left">常规操作</el-divider>
        <el-row :gutter="10" style="width:800px;">
          <!-- <el-col :span="12" class="menu-list" v-if="excelInfoShow"> -->

          <el-col :span="6" class="menu-list">
            <!-- <div @click="createSeaAirMerge" >创建合单 </div> -->
            <div @click="toUploadfile" v-if="permission('to_upload_file')">
              上传文件
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div @click="toMergeAllEdit" v-if="permission('to_merge_all_edit')">
              合单全编辑
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="toHdEditOne('fileList')"
              v-if="permission('file_list')"
            >
              文件列表
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="
                downLoadFile('exportOutboundTable', '导出海运出库表', '', '')
              "
              v-if="
                permission('export_outbound_table') &&
                  (this.data['shippingWay'] == 'FCL' ||
                    this.data['shippingWay'] == 'LCL')
              "
            >
              导出海运出库表
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="
                downLoadFile(
                  'exportMergePackingInvoice',
                  '导出分单箱单发票',
                  '',
                  ''
                )
              "
              v-if="permission('export_merge_packing_invoice')"
            >
              导出分单箱单发票
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="
                exportManifestLigentia(
                  'exportManifestLigentia',
                  '导出海运MANIFEST',
                  '',
                  ''
                )
              "
              v-if="
                permission('export_manifest_ligentia') &&
                  (this.data['shippingWay'] == 'FCL' ||
                    this.data['shippingWay'] == 'LCL')
              "
            >
              导出海运MANIFEST
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="toliquidationInvoice"
              v-if="permission('to_liquidation_invoice')"
            >
              清关发票
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="postParamsEdit('wayBillMergerLock', '锁定', 'param5', 1)"
              v-if="permission('waybill_merger_lock')"
            >
              合单锁单
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="postParamsEdit('wayBillMergerLock', '锁定', 'param5', 0)"
              v-if="permission('waybill_merger_lock')"
            >
              合单解锁
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="toHdEditOne('receivable')"
              v-if="permission('receivable')"
            >
              应收应付
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="toallocationtrace"
              v-if="permission('to_allocation_trace')"
            >
              分配轨迹
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="postEdit('waybillMergeTrackBack', '打回轨迹')"
              v-if="
                permission('waybill_merge_track_back') &&
                  this.data['status'] > 50 &&
                  this.data['status'] < 888
              "
            >
              打回轨迹
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="tobatchmergetrack"
              v-if="permission('to_batch_merge_track')"
            >
              批量打回轨迹
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="toWaybillMergeSysRemark"
              v-if="permission('to_waybill_merge_remark')"
            >
              合单备注
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="
                postEdit('synchronWaybillMergeDataToSingle', '同步分单数据')
              "
              v-if="permission('synchron_to_single')"
            >
              同步分单数据
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="toEditOverseasOperator"
              v-if="
                permission('to_edit_overseas_operator') &&
                  (this.data['shippingWay'] == 'FCL' ||
                    this.data['shippingWay'] == 'LCL')
              "
            >
              修改海外操作
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="postEdit('deleteWaybillMerge', '删除')"
              v-if="permission('delete_waybill_merge')"
            >
              删除
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="toAddSimpleWaybillRemark"
              v-if="permission('to_add_simple_waybill_remark')"
            >
              增加备注
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="postEdit('pushWaybillMergeToAgent', '推送至代理')"
              v-if="permission('push_waybill_merge_to_agent')"
            >
              <!--清关服务商或者代理服务商-->
              推送至代理({{ agentMap[data["customsClearanceAgent"]] }})
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="postEdit('pushWaybillMergeToAgent', '推送至代理')"
              v-if="permission('push_waybill_merge_to_agent')"
            >
              <!--清关服务商或者代理服务商-->
              推送至派送服务({{ agentMap[data["afterSendServicer"]] }})
            </div>
          </el-col>
          <el-col :span="6" class="menu-list">
            <div
              @click="amsDeclare()"
              v-if="
                permission('ams_declare') &&
                  (this.data['shippingWay'] == 'FCL' ||
                    this.data['shippingWay'] == 'FCLG')
              "
            >
              AMS申报
            </div>
          </el-col>
          <el-col
            :span="6"
            v-for="(item, k) in excelFileInfos"
            :key="k"
            class="menu-list"
          >
            <div @click="exportSingleTicket(item.id, item.fileName, item)">
              导出{{ item.fileName }}
            </div>
          </el-col>
        </el-row>

        <div slot="reference">
          <span class="text-blue">更多</span>
        </div>
      </el-popover>
    </div>

    <AddSimpleWaybillRemark
      ref="AddSimpleWaybillRemark"
      :data="data"
    ></AddSimpleWaybillRemark>
    <EditOverseasOperator
      ref="EditOverseasOperator"
      :data="data"
      :userOptions="userOptions"
    ></EditOverseasOperator>
    <Uploadfile
      ref="Uploadfile"
      :data="data"
      :fileTypeOptions="fileTypeOptions"
    ></Uploadfile>
  </div>
</template>

<script>
import { Loading } from "element-ui";
import { ajax, actionPermission } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { m } from "@/store/yg/common/local";
const AddSimpleWaybillRemark = () =>
  import("./mergepage/AddSimpleWaybillRemark");
const EditOverseasOperator = () => import("./mergepage/EditOverseasOperator");
const Uploadfile = () => import("./mergepage/Uploadfile");
const CreateMergeEdit = () => import("./editpage/CreateMergeEdit");

export default {
  components: {
    AddSimpleWaybillRemark,
    EditOverseasOperator,
    Uploadfile,
    CreateMergeEdit
  },
  data() {
    return {
      fullscreenLoading: false,
      createmergeShow: false,
      agentMap: {},
      disabled: false,
      excelFileInfos: [],
      excelInfoShow: false,
      shippingWay: "",
      userOptions: {},
      fileTypeOptions: {},
      createMergeData: {},
      loaded: false,
      fiveExcelFileInfos: [],
      rules: {}
    };
  },
  props: ["row", "data", "more"],
  computed: {},
  mounted() {
    this.intitExcelFileInfos(0);
    this.fetchAgentApi();
    if (this.data["customsClearanceAgent"] && this.data["hasBeenPushed"] == 0) {
      this.disabled = true;
    }
    if (this.data["afterSendServicer"] && this.data["hasBeenPushed"] == 0) {
      this.disabled = true;
    }
    this.displayRules();
  },
  methods: {
    displayRules() {
      this.loaded = false;
      this.rules = {};
      var uri = "/waybill/seafreightmerge/list";
      if (this.shippingWay == "AIR" || this.shippingWay == "ZX") {
        uri = "/waybill/airfreightmerge/list";
      } else if (this.shippingWay == "LCL" || this.shippingWay == "FCL") {
        var uri = "/waybill/seafreightmerge/list";
      }
      if (
        !this.$store.state.main.entry ||
        this.$store.state.main.entry.uri != uri
      ) {
        let mainUri = "/api/entry/main?uri=" + uri;

        axios
          .post(constant.API_SERVER + mainUri)
          .then(response => {
            response.data.table.action.forEach(element => {
              if (element.displayRule) {
                this.rules[element.client.commit] = element.displayRule;
              }
            });
            this.loaded = true;
          })
          .catch(error => {});
      } else {
        for (var i in this.$store.state.main.entry.table.action) {
          let a = this.$store.state.main.entry.table.action[i];
          if (a.displayRule) {
            this.rules[a.client.commit] = a.displayRule;
          }
        }
        this.loaded = true;
      }
    },
    // 初始化 下载
    fetchAgentApi() {
      var param = {};
      var key = "agent_api_init";
      var agents = JSON.parse(sessionStorage.getItem(key));

      if (!agents || agents == "{}" || agents == null || agents == "null") {
        ajax("fetchAgentApi", param).then(
          res => {
            if (res.code == 200) {
              this.agentMap = res.data;
              sessionStorage.setItem(key, JSON.stringify(this.agentMap));
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        this.agentMap = agents;
      }
    },

    exportManifestLigentia(postUrl, info, paramsName, params) {
      this.$confirm("此操作将" + info + ", 是否继续？")
        .then(_ => {
          // TODO 保存操作
          var param = {};
          param["id"] = this.data["id"];
          if (
            null != paramsName &&
            "" != paramsName &&
            null != params &&
            "" != params
          ) {
            param[paramsName] = params;
          }
          ajax(postUrl, param).then(
            res => {
              console.log(res);
              if (res.errorMesage != null && res.errorMesage != "") {
                this.$message.error(res.errorMesage);
              } else {
                var path = (path = constant.FILE_SERVER + res.path);
                var fileUrl = path + res.fileName;
                location.href =
                  constant.API_SERVER +
                  "/open/downloadFileByHttp?fileName=" +
                  fileName +
                  "&path=" +
                  fileUrl;
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(_ => {});
    },

    exportSingleTicket(excelFileId, fileName, item) {
      var fiveKey = "five_excel_init_m" + this.shippingWay;
      var fiveInfos = JSON.parse(sessionStorage.getItem(fiveKey));
      //首先看当前 点击是否已经在缓存里面 如果在 向前移动
      //如果不存在 删除首位 放在末位 数组先入的在最下面
      if (fiveInfos && fiveInfos.length > 0) {
        var checckExit = false;
        for (let index = 0; index < fiveInfos.length; index++) {
          const element = fiveInfos[index];
          if (excelFileId === element.id) {
            fiveInfos.splice(index, 1);
            checckExit = true;
          }
        }
        if (!checckExit) {
          fiveInfos.splice(0, 1);
        }
      } else {
        fiveInfos = [];
      }
      fiveInfos.push(item);
      sessionStorage.setItem(fiveKey, JSON.stringify(fiveInfos));

      var param = {};
      param["statementTemplateId"] = excelFileId;
      // param["shippingWay"] = this.data['shippingWay'];
      param["waybillId"] = this.data["id"];
      // param["code"] = "M";
      // console.info('excelFileId',param);
      this.fullscreenLoading = true;
      const attrs = {
        class: "com.tofba.app.client.statistics.StatementExportClient"
      };
      ajax("exportSingleVoteStatementDataFile", param, attrs).then(
        res => {
          console.log(res);
          this.fullscreenLoading = false;
          if (res.code == 200) {
            var path = (path = constant.FILE_SERVER + res.message);
            if (res.message) {
              fileName = res.message.substring(
                res.message.lastIndexOf("/") + 1,
                res.message.length
              );
            }
            location.href =
              constant.API_SERVER +
              "/open/downloadFileByHttp?fileName=" +
              fileName +
              "&path=" +
              path;
          } else {
            if (null != res.message) {
              this.$message.error("导出失败原因：" + res.message);
            } else {
              this.$message.error("导出失败");
            }
          }
        },
        error => {
          this.fullscreenLoading = false;
          console.log(error);
        }
      );
    },

    // 初始化 下载
    intitExcelFileInfos(loadType) {
      var param = {};
      this.shippingWay = this.data["shippingWay"];
      var key = "excel_init_M" + this.shippingWay;
      var fileInfos = JSON.parse(sessionStorage.getItem(key));

      var fiveKey = "five_excel_init_m" + this.shippingWay;
      var fiveInfos = JSON.parse(sessionStorage.getItem(fiveKey));

      if (
        loadType == 1 ||
        !fileInfos ||
        fileInfos == "{}" ||
        null == fileInfos ||
        "null" == fileInfos
      ) {
        param["code"] = "M";
        param["shippingWayType"] = this.shippingWay;
        ajax("intitExcelFileInfos", param).then(
          res => {
            this.excelInfoShow = true;
            if (res.code == 200) {
              this.excelFileInfos = res.data;
              sessionStorage.setItem(key, JSON.stringify(this.excelFileInfos));
              if (this.excelFileInfos && this.excelFileInfos.length > 0) {
                if (!fiveInfos || fiveInfos.length == 0) {
                  fiveInfos = [];
                  if (this.excelFileInfos.length > 5) {
                    for (let index = 0; index < 5; index++) {
                      const nowExcelFile = this.excelFileInfos[index];
                      fiveInfos.push(nowExcelFile);
                    }
                  } else {
                    fiveInfos = this.excelFileInfos;
                  }
                }
                sessionStorage.setItem(fiveKey, JSON.stringify(fiveInfos));
                this.fiveExcelFileInfos = fiveInfos;
                this.excelInfoShow = true;
              }
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        if (fileInfos && fileInfos.length > 0) {
          if (!fiveInfos || fiveInfos.length == 0) {
            fiveInfos = [];
            if (fileInfos.length > 5) {
              for (let index = 0; index < 5; index++) {
                const nowExcelFile = fileInfos[index];
                fiveInfos.push(nowExcelFile);
              }
            } else {
              fiveInfos = fileInfos;
            }
            sessionStorage.setItem(fiveKey, JSON.stringify(fiveInfos));
          }
          this.fiveExcelFileInfos = fiveInfos;
          this.excelInfoShow = true;
        }
        this.excelFileInfos = fileInfos;
      }
    },
    permission(commit) {
      return actionPermission(this.rules, commit, this.data, this.$store.state);
    },
    //上传文件
    toUploadfile() {
      this.$refs.Uploadfile.centerDialogVisible = true;
      var uri = "/api/entry/source?bean=" + "fileTypeSource";
      axios.post(constant.API_SERVER + uri).then(
        response => {
          this.fileTypeOptions = response.data;
        },
        error => {
          console.info(error);
        }
      );
    },
    downLoadFile(postUrl, info, paramsName, params) {
      this.$confirm("此操作将" + info + ", 是否继续？")
        .then(_ => {
          // TODO 保存操作
          var param = {};
          param["id"] = this.data["id"];
          if (
            null != paramsName &&
            "" != paramsName &&
            null != params &&
            "" != params
          ) {
            param[paramsName] = params;
          }
          ajax(postUrl, param).then(
            res => {
              console.log(res);
              if (res.message != null && res.message != "") {
                this.$message.error(res.message);
              } else if (res.errorMesage != null && res.errorMesage != "") {
                this.$message.error(res.errorMesage);
              } else {
                var path = (path = constant.FILE_SERVER + res.path);
                var fileUrl = path + res.fileName;
                console.log(fileUrl);
                window.open(fileUrl);
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(_ => {});
    },
    //清关发票
    toliquidationInvoice() {
      const url = "#/blank/waybill__liquidationInvoice__main";
      // this.$store.dispatch("loadBlankEntry", url);
      window.open(url + "?waybillId=" + this.data["id"], "_blank");
      //获取当前路由地址
      // const urlPath = this.$route.path;
      // if(urlPath.indexOf("waybill__seafreightmerge__list") >= 0){
      //     //console.info('这是海运合单');
      //     const url = '#/blank/waybill__seafreightmerge__main';
      //     this.$store.dispatch("loadBlankEntry", url);
      //     location.href = url +'?shippingway=0&waybillId='+this.data['id'];

      // }else if(urlPath.indexOf("waybill__airfreightmerge__list") >= 0){
      //     //console.info('这是空运合单');
      //     const url = '#/blank/waybill__airfreightmerge__main';
      //     this.$store.dispatch("loadBlankEntry", url);
      //     location.href = url +'?shippingway=1&waybillId='+this.data['id'];
      // }
    },
    createSeaAirMerge() {
      this.$refs.CreateMergeEdit.centerDialogVisible = true;
    },
    toMergeAllEdit() {
      //获取当前路由地址
      const urlPath = this.$route.path;
      if (urlPath.indexOf("waybill__seafreightmerge__list") >= 0) {
        //console.info('这是海运合单');
        var url = "#/blank/waybill__seafreightmerge__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url = url + "?shippingway=0&waybillId=" + this.data["id"];
        window.open(url, "_blank");
      } else if (urlPath.indexOf("waybill__airfreightmerge__list") >= 0) {
        //console.info('这是空运合单');
        var url = "#/blank/waybill__airfreightmerge__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url = url + "?shippingway=1&waybillId=" + this.data["id"];
        window.open(url, "_blank");
      } else {
        var url = "#/blank/waybill__airfreightmerge__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url = url + "?shippingway=1&waybillId=" + this.data["id"];
        window.open(url, "_blank");
      }
    },

    toHdEditOne(activeName) {
      //获取当前路由地址
      const urlPath = this.$route.path;
      if (urlPath.indexOf("waybill__seafreightmerge__list") >= 0) {
        //console.info('这是海运合单');
        var url = "#/blank/waybill__seafreightmerge__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url =
          url +
          "?shippingway=0&waybillId=" +
          this.data["id"] +
          "&activeName=" +
          activeName;
        window.open(url, "_blank");
      } else if (urlPath.indexOf("waybill__airfreightmerge__list") >= 0) {
        //console.info('这是空运合单');
        var url = "#/blank/waybill__airfreightmerge__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url =
          url +
          "?shippingway=1&waybillId=" +
          this.data["id"] +
          "&activeName=" +
          activeName;
        window.open(url, "_blank");
      } else {
        //console.info('这是空运合单');
        var url = "#/blank/waybill__airfreightmerge__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url =
          url +
          "?shippingway=1&waybillId=" +
          this.data["id"] +
          "&activeName=" +
          activeName;
        window.open(url, "_blank");
      }
    },

    //合单备注
    toWaybillMergeSysRemark() {
      var url = "#/blank/waybill__mergewaybillremark__main";
      // this.$nextTick(()=>{
      // this.$store.dispatch("loadBlankEntry", url);
      //location.href = url;
      window.open(url + "?waybillId=" + this.data["id"], "_blank");
      //this.$store.dispatch('loadBlankEntry', url);

      // })
    },

    //分配轨迹
    toallocationtrace() {
      const url = "#/blank/waybill__allocationtrace__main";
      // this.$store.dispatch("loadBlankEntry", url);
      //location.href = url;
      window.open(url + "?waybillId=" + this.data["id"], "_blank");
      //this.$store.dispatch('loadBlankEntry', url);

      // })
    },

    //批量打回轨迹
    tobatchmergetrack() {
      const url = "#/blank/waybill__batchmergetrack__main";
      // this.$store.dispatch("loadBlankEntry", url);
      //location.href = url;
      window.open(url + "?waybillId=" + this.data["id"], "_blank");
      //this.$store.dispatch('loadBlankEntry', url);

      // })
    },

    //增加备注
    toAddSimpleWaybillRemark() {
      this.$refs.AddSimpleWaybillRemark.centerDialogVisible = true;
    },

    //修改海外操作
    toEditOverseasOperator() {
      this.$refs.EditOverseasOperator.centerDialogVisible = true;
      var uri = "/api/entry/source?bean=userSource";
      axios.post(constant.API_SERVER + uri).then(
        response => {
          this.userOptions = response.data;
        },
        error => {
          console.info(error);
        }
      );
    },
    amsDeclare() {
      this.$confirm("确认是否进行AMS申报?")
        .then(_ => {
          var param = {};
          param["id"] = this.data["id"];
          ajax("amsDeclare", param).then(
            res => {
              if (res.code === 200) {
                this.$message.success("AMS申报成功");
              } else {
                this.$message.error("AMS申报失败:" + res.message);
              }
            },
            error => {
              console.log(error);
              this.$message.success("AMS申报接口内部异常");
            }
          );
        })
        .catch(_ => {});
    },

    postParamsEdit(postUrl, info, paramsName, params) {
      this.$confirm("此操作将" + info + ", 是否继续？")
        .then(_ => {
          // TODO 保存操作
          var param = {};
          param["id"] = this.data["id"];
          param["status"] = this.data["status"];
          param[paramsName] = params;
          ajax(postUrl, param).then(
            res => {
              if (res.code != 200) {
                if (null != res.message) {
                  this.$message.error(m(res.message));
                } else {
                  this.$message.error("修改失败!");
                }
              } else {
                this.$message.success("修改成功!");
                this.centerDialogVisible = false;
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(_ => {});
    },
    //公共的后台请求
    postEdit(postUrl, info) {
      this.$confirm("此操作将" + info + ", 是否继续？")
        .then(_ => {
          // TODO 保存操作
          var param = {};
          param["id"] = this.data["id"];
          param["status"] = this.data["status"];
          ajax(postUrl, param).then(
            res => {
              if (res.code != 200) {
                if (null != res.message) {
                  this.$message.error(m(res.message));
                } else {
                  this.$message.error("修改失败!");
                }
              } else {
                this.$message.success("修改成功!");
                this.centerDialogVisible = false;
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(_ => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.menu-list {
  min-width: 12vw;
  max-height: 90vh;
  overflow-y: auto;
  div {
    padding: 6px 8px;
    cursor: pointer;
    font-size: 12px;
    &:hover {
      background: #51abd1;
      color: #fff;
    }
  }
}
.letter {
  letter-spacing: -2px;
}
.icon-border {
  display: inline-block;
  border: 1px solid;
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
}
</style>
